<?php
namespace App\Api\Controllers\AlipayOpen;


use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipayOpenAuthTokenAppRequest;
use Alipayopen\Sdk\Request\AlipaySystemOauthTokenRequest;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use App\Models\AlipayAppOauthUsers;
use App\Models\MemberList;
use App\Models\MemberSetJf;
use App\Models\MemberTpl;
use App\Models\Store;
use App\Models\StorePayWay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OauthController extends BaseController
{

    //支付宝回调处理
    public function callback(Request $request)
    {
        try {
            $state = $this->decode($request->get('state'));
            //Log::info('支付宝正扫授权回调参数: '.str_replace("\\/", "/", json_encode($state, JSON_UNESCAPED_UNICODE)));
            if (empty($state)) {
                $message = '授权失败';
                return view('errors.page_errors', compact('message'));
            }

            // 商户授权
            if ($state['auth_type'] == '01') {
                $state['app_auth_code'] = $request->get('app_auth_code');

                return $this->merchantAuth($state);
            }

            // 用户授权
            if ($state['auth_type'] == '02') {
                return $this->memberAuth($request->get('auth_code'), $state);
            }

            // 学校商户第三方授权授权
            if ($state['auth_type'] == '03') {
                $state['app_auth_code'] = $request->get('app_auth_code');

                return $this->merchantAuth($state);
            }

            $message = 'auth_type类型错误';

            return view('errors.page_errors', compact('message'));
        } catch (\Exception $e) {
            $message = '系统错误！' . $e->getMessage() . $e->getFile() . $e->getLine();
            return view('errors.page_errors', compact('message'));
        }
    }


    // 用户授权
    public function memberAuth($app_auth_code, $state)
    {
        $member_return = $this->memberAliInfo($app_auth_code, $state);

        if ($member_return['status'] != 1) {
            exit($member_return['message']);
        }

        $open_id = $member_return['data']['open_id'];
	    //Log::info('支付宝用户授权: '.str_replace("\\/", "/", json_encode($state, JSON_UNESCAPED_UNICODE)));
        switch ($state['bank_type']) {
            case 'alipay':
                return self::alipay('alipay', $state, $open_id);
                break;
            case 'mbalipay':
                return self::alipay('mbalipay', $state, $open_id);
                break;
            case 'jdalipay':
                return self::alipay('jdalipay', $state, $open_id);
                break;
            case 'lftalipay':
                return self::alipay('lftalipay', $state, $open_id);
                break;
            case 'nlalipay':
                return self::alipay('nlalipay', $state, $open_id);
                break;
            case 'halipay':
                return self::alipay('halipay', $state, $open_id);
                break;
            case 'fuioualipay':
                return self::alipay('fuioualipay', $state, $open_id);
                break;
            case 'dlb_alipay':
                return self::alipay('dlb_alipay', $state, $open_id);
                break;
            case 'tfpay_alipay':
                return self::alipay('tfpay_alipay', $state, $open_id);
                break;
            case 'vbill_alipay':
                return self::alipay('vbill_alipay', $state, $open_id);
                break;
            case 'vbill1_alipay':
                return self::alipay('vbill1_alipay', $state, $open_id);
                break;
	        case 'huipay_alipay':
                $state['auth_code'] = $app_auth_code;
                return self::alipay('huipay_alipay', $state, $open_id);
                break;
            case 'vbilla_alipay':
                return self::alipay('vbilla_alipay', $state, $open_id);
                break;
	        case 'hkrt_alipay':
                return self::alipay('hkrt_alipay', $state, $open_id);
                break;
            case 'easypay_alipay':
                return self::alipay('easypay_alipay', $state, $open_id);
                break;
            case 'easypaya_alipay':
                return self::alipay('easypaya_alipay', $state, $open_id);
                break;
            case 'linkage_alipay':
                return self::alipay('linkage_alipay', $state, $open_id);
                break;
            case 'zft_alipay':
                return self::alipay('zft_alipay', $state, $open_id);
                break;
            case 'hltx_alipay':
                return self::alipay('hltx_alipay', $state, $open_id);
                break;
            case 'wftpay_alipay':
                return self::alipay('wftpay_alipay', $state, $open_id);
            case 'wftpayv2_alipay':
                return self::alipay('wftpayv2_alipay', $state, $open_id);
                break;
            case 'hwcpay_alipay':
                return self::alipay('hwcpay_alipay', $state, $open_id);
                break;
            case 'wing_alipay':
                return self::alipay('wing_alipay', $state, $open_id);
                break;
            case 'safe_alipay':
                return self::alipay('safe_alipay', $state, $open_id);
                break;
            case 'you_alipay':
                return self::alipay('you_alipay', $state, $open_id);
                break;
            case 'jiujiang_alipay':
                return self::alipay('jiujiang_alipay', $state, $open_id);
                break;
             case 'cib_alipay':
                return self::alipay('cib_alipay', $state, $open_id);
                break;
             case 'yinka_alipay':
                return self::alipay('yinka_alipay', $state, $open_id);
                break;
            case 'yinsheng_alipay':
                return self::alipay('yinsheng_alipay', $state, $open_id);
                break;
            case 'dongguan_alipay':
                return self::alipay('dongguan_alipay', $state, $open_id);
                break;
            case 'cmbc_alipay':
                return self::alipay('cmbc_alipay', $state, $open_id);
                break;
            case 'lakalaunion_alipay':
                return self::alipay('lakalaunion_alipay', $state, $open_id);
                break;
            case 'leshuaunion_alipay':
                return self::alipay('leshuaunion_alipay', $state, $open_id);
                break;
            case 'gtxy_alipay':
                return self::alipay('gtxy_alipay', $state, $open_id);
            case 'gtxy_v2_alipay':
                return self::alipay('gtxy_v2_alipay', $state, $open_id);
            default :
                return self::alipay($state['bank_type'], $state, $open_id);
                $message = '银行类型未传递！';
                return view('errors.page_errors', compact('message'));
        }

    }


    // 商户授权
    public function merchantAuth($state)
    {
        $config = $this->isv_config($state['config_id']);
        //1.接入参数初始化
        $c = new AopClient();
        $c->signType = "RSA2";//升级算法
        $c->gatewayUrl = $config->alipay_gateway;
        $c->appId = $config->app_id;
        $c->rsaPrivateKey = $config->rsa_private_key;
        $c->format = "json";
        $c->charset = "GBK";
        $c->version = "2.0";

        //2.执行相应的接口获得相应的业务
        $obj = new AlipayOpenAuthTokenAppRequest();
        $obj->setApiVersion('2.0');
        $obj->setBizContent("{" .
            "    \"grant_type\":\"authorization_code\"," .
            "    \"code\":\"" . $state['app_auth_code'] . "\"," .
            "  }");

        try {
            $data = $c->execute($obj);
            $app_response = $data->alipay_open_auth_token_app_response;
        } catch (\Exception $exception) {
            $message = '配置出错检查一下支付宝应用配置！' . $exception->getMessage();

            return view('errors.page_errors', compact('message'));
        }

        $app_response = (array)$app_response;
        $code = $app_response['code'];
        if ($code == 10000) {
            $model = [
                "alipay_user_id" => $app_response['user_id'],
                'alipay_user_account' => $app_response['user_id'],
                "store_id" => $state['store_id'],
                'merchant_id' => 1,
                "app_auth_token" => $app_response['app_auth_token'],
                "app_refresh_token" => $app_response['app_refresh_token'],
                "expires_in" => $app_response['expires_in'],
                "re_expires_in" => $app_response['re_expires_in'],
                "auth_app_id" => $app_response['auth_app_id'],
            ];
            $alipay_user = AlipayAppOauthUsers::where('store_id', $state['store_id'])
                ->where('config_type', '01')
                ->first();

            //开启事务
            try {
                DB::beginTransaction();
                if ($alipay_user) {
                    AlipayAppOauthUsers::where('store_id', $state['store_id'])->update($model);

                    //新增通道
                    $a_w = StorePayWay::where('store_id', $state['store_id'])
                        ->where('ways_type', 1000)
                        ->first();

                    if ($a_w) {
                        $data_inset = [
                            'store_id' => $state['store_id'],
                            'status' => 1,
                            'status_desc' => '开通成功',
                        ];
                        $a_w->update($data_inset);
                        $a_w->save();
                    } else {
                        $gets1 = StorePayWay::where('store_id', $state['store_id'])->where('ways_source', 'alipay')->where('status', 1)->get();
                        $count1 = count($gets1);

                        $data_inset = [
                            'store_id' => $state['store_id'],
                            'settlement_type' => 'D0',
                            'ways_type' => 1000,
                            'company' => 'alipay',
                            'ways_source' => 'alipay',
                            'ways_desc' => '支付宝',
                            'ta_rate' => 0.6,
                            'tb_rate' => 0.6,
                            'sort' => $count1 + 1,
                            'status' => 1,
                            'status_desc' => '开通成功',
                        ];
                        StorePayWay::create($data_inset);
                    }
                } else {
                    AlipayAppOauthUsers::create($model); //新增信息
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $message = '配置出错检查一下支付宝应用配置！' . $e->getMessage().' | '.$e->getFile().' | '.$e->getLine();
                return view('errors.page_errors', compact('message'));
            }
        } else {
            $message = '配置出错检查一下支付宝应用配置！';
            return view('errors.page_errors', compact('message'));
        }

        if ($state['auth_type'] == '03') {
            //支付宝教育缴费平台需要获得学校授权，因为由教育缴费平台代替学校向支付宝发起支付操作
            return redirect($config->alipay_school_auth_url);
        }

        $message = '授权成功！';
        return view('success.success', compact('message'));
    }


    //支付宝视图页面
    public static function alipay($type, $state, $open_id)
    {
        $store_id = $state['store_id'];//门店id
        $merchant_id = $state['merchant_id'];//收银员id
        $store_name = $state['store_name'];
        $store_address = $state['store_address'];
        $data = [
            'store_id' => $store_id,
            'store_name' => $store_name,
            'store_address' => $store_address,
            'open_id' => $open_id,
            'merchant_id' => $merchant_id,
            'other_no' => isset($state['other_no']) ? $state['other_no'] : "",
            'notify_url' => isset($state['notify_url']) ? $state['notify_url'] : "",
        ];

        //查询是否有开启会员
        $is_member = 0;
        $MemberTpl = MemberTpl::where('store_id', $store_id)
            ->select('tpl_status')
            ->first();
        if ($MemberTpl && $MemberTpl->tpl_status == 1) {
            $is_member = 1;
        }

        //如果是会员
        if ($is_member) {
            //判断是否是会员
            $ali_user_id = $open_id;
            $MemberList = MemberList::where('store_id', $store_id)
                ->where('ali_user_id', $ali_user_id)
                ->select('mb_jf', 'mb_money', 'mb_id','mb_phone')
                ->first();
            $data['mb_jf'] = "";
            $data['mb_id'] = "";
            $data['mb_money'] = "";
            $data['dk_money'] = "";
            $data['dk_jf'] = "0";
            $data['ways_source'] = "alipay";
            $data['is_info'] = "0";//信息补全
            if ($MemberList) {
                $data['mb_jf'] = $MemberList->mb_jf;
                $data['mb_id'] = $MemberList->mb_id;
                $data['mb_money'] = $MemberList->mb_money;

                if($MemberList->mb_phone){
                    $data['is_info'] = "1";
                }

                //判断是否有积分抵扣
                $MemberSetJf = MemberSetJf::where('store_id', $store_id)
                    ->select('dk_jf_m', 'dk_rmb')
                    ->first();
                if ($MemberSetJf) {
                    //3.用户的积分一共可以抵扣多少钱
                    $data['dk_money'] = ($MemberList->mb_jf / $MemberSetJf->dk_jf_m) * $MemberSetJf->dk_rmb;
                    $data['dk_jf'] = $MemberList->mb_jf;
                }
            }
        }

        //支付宝 官方
        if ($type == 'alipay') {
            //会员视图
            if ($is_member) {
                $data['ways_type'] = "1000";
                $data['company'] = "alipay";

                return view('member.alipay', compact('data'));
            } else {
                return view('alipayopen.create_alipay_order', compact('data'));
            }

        }

        //支付宝 支付通
        if ($type == 'zft_alipay') {
            //会员视图
            if ($is_member) {
                $data['ways_type'] = "16002";
                $data['company'] = "zft";

                return view('member.zft_alipay', compact('data'));
            } else {
                return view('alipayopen.zft_alipay', compact('data'));
            }

        }

        //网商 支付宝
        if ($type == 'mbalipay') {
            //会员视图
            if ($is_member) {
                $data['ways_type'] = "3001";
                $data['company'] = "mybank";
                return view('member.mbalipay', compact('data'));
            } else {
                return view('mybank.alipay', compact('data'));
            }
        }

        //京东 支付宝
        if ($type == 'jdalipay') {
            //会员视图
            if ($is_member) {
                $data['ways_type'] = "6001";
                $data['company'] = "jdjr";
                return view('member.jdalipay', compact('data'));
            } else {
                return view('jd.alipay', compact('data'));
            }
        }

        //联付通
        if ($type == 'lftalipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "10001";
                $data['company'] = "ltf";
                return view('member.ltfalipay', compact('data'));
            } else {
                return view('lft.alipay', compact('data'));
            }
        }

        //新大陆
        if ($type == 'nlalipay') {
            if ($is_member) {
                $data['ways_type'] = "8001";
                $data['company'] = "newland";
                return view('member.nlalipay', compact('data'));
            } else {
                return view('newland.alipay', compact('data'));
            }
        }

        //会员宝
        if ($type == 'halipay') {
            if ($is_member) {
                $data['ways_type'] = "9001";
                $data['company'] = "herongtong";
                return view('member.halipay', compact('data'));
            } else {
                return view('huiyuanbao.alipay', compact('data'));
            }
        }

        //富友
        if ($type == 'fuioualipay') {
            if (0) {
                $data['ways_type'] = "11001";
                $data['company'] = "fuiou";
                return view('member.fuioualipay', compact('data'));
            } else {
                return view('fuiou.alipay', compact('data'));
            }
        }

        //哆啦宝
        if ($type == 'dlb_alipay') {
            //会员视图
            if ($is_member) {
                $data['ways_type'] = "15001";
                $data['company'] = "dlb";
                return view('dlb.memberalipay', compact('data'));
            } else {
                return view('dlb.alipay', compact('data'));
            }
        }

        //传化TF
        if ($type == 'tfpay_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "12001";
                $data['company'] = "tfpay";
                return view('tfpay.memberalipay', compact('data'));
            } else {
                return view('tfpay.alipay', compact('data'));
            }
        }

        //随行付
        if ($type == 'vbill_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "13001";
                $data['company'] = "vbill";
                return view('vbill.memberalipay', compact('data'));
            } else {
                return view('vbill.alipay', compact('data'));
            }
        }
        
        //随行付
        if ($type == 'vbill1_alipay') {
            return view('vbill.merch_qr', compact('data'));
        }
        
        //翼支付
        if ($type == 'wing_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "30051";
                $data['company'] = "wingpay";
                return view('vbill.memberalipay', compact('data'));
            } else {
                return view('vbill.wingalipay', compact('data'));
            }
        }
        
        //平安银行
        if ($type == 'safe_alipay') {
            return view('vbill.safealipay', compact('data'));
        }
        
        //平安银行
        if ($type == 'you_alipay') {
            return view('vbill.youalipay', compact('data'));
        }

        //汇付
	    if ($type == 'huipay_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "18001";
                $data['company'] = "huipay";
                return view('huipay.memberalipay', compact('data'));
            } else {
                return view('huipay.alipay', compact('data'));
            }
        }

        //随心付a
        if ($type == 'vbilla_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "19001";
                $data['company'] = "vbilla";
                return view('vbilla.memberalipay', compact('data'));
            } else {
                return view('vbilla.alipay', compact('data'));
            }
        }

        //海科融通
	    if ($type == 'hkrt_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "22001";
                $data['company'] = "hkrt";
                return view('hkrt.memberalipay', compact('data'));
            } else {
                return view('hkrt.alipay', compact('data'));
            }
        }

        //易生
        if ($type == 'easypay_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "21001";
                $data['company'] = "easypay";
                return view('easypay.memberalipay', compact('data'));
            } else {
                return view('easypay.alipay', compact('data'));
            }
        }

        //易生
        if ($type == 'easypaya_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "61001";
                $data['company'] = "easypaya";
                return view('easypaya.memberalipay', compact('data'));
            } else {
                return view('easypaya.alipay', compact('data'));
            }
        }

        //联动优势
        if ($type == 'linkage_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "5001";
                $data['company'] = "linkage";
                return view('linkage.memberalipay', compact('data'));
            } else {
                return view('linkage.alipay', compact('data'));
            }
        }
        
        // 九江银行
        if ($type == 'jiujiang_alipay') {
            //会员视图
            // if (0) {
            //     $data['ways_type'] = "37002";
            //     $data['company'] = "jiujiang";
            //     return view('linkage.memberalipay', compact('data'));
            // } else {
            // print_r(2);die;
            return view('jiujiang.alipay', compact('data'));
            // }
        }

        //瑞银信（葫芦天下）
        if ($type == 'hltx_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "23001";
                $data['company'] = "hltx";
                return view('hltx.memberalipay', compact('data'));
            } else {
                return view('hltx.alipay', compact('data'));
            }
        }

        //威富通
        if ($type == 'wftpay_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "27001";
                $data['company'] = "wftpay";
                return view('wftpay.memberalipay', compact('data'));
            } else {
                return view('wftpay.alipay', compact('data'));
            }
        }
        if ($type == 'wftpayv2_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "27101";
                $data['company'] = "wftpayv2";
                return view('wftpayv2.memberalipay', compact('data'));
            } else {
                return view('wftpayv2.alipay', compact('data'));
            }
        }

        //汇旺财
        if ($type == 'hwcpay_alipay') {
            //会员视图
            if (0) {
                $data['ways_type'] = "28001";
                $data['company'] = "hwcpay";
                return view('hwcpay.memberalipay', compact('data'));
            } else {
                return view('hwcpay.alipay', compact('data'));
            }
        }
        
         //兴业银行
		if ($type == 'cib_alipay') {
			return view('cib.alipay', compact('data'));
		}

        //兴业银行
        if ($type == 'cmbc_alipay') {
            return view('cmbc.alipay', compact('data'));
        }

        //gtxy
        if ($type == 'gtxy_alipay') {
            return view('gtxy.alipay', compact('data'));
        }
        //gtxy
        if ($type == 'gtxy_v2_alipay') {
            return view('gtxy_v2.alipay', compact('data'));
        }
        if($type=="lakalaunion_alipay"){
            return view('lakalaunion.alipay', compact('data'));
        }

        if($type=="leshuaunion_alipay"){
            return view('leshuaunion.alipay', compact('data'));
        }
		  //银卡
		if ($type == 'yinka_alipay') {
			return view('yinka.alipay', compact('data'));
		}

        //银胜
        if ($type == 'yinsheng_alipay') {
            return view('yinsheng.alipay', compact('data'));
        }

        //东莞
        if ($type == 'dongguan_alipay') {
            return view('dong_guan.alipay', compact('data'));
        }

        if ($type == 'cmbcunion_alipay') {
            return view('cmbcUnion.alipay', compact('data'));
        }

        $path = implode('.', explode('_', $type));

        return view($path, compact('data'));

    }


    public function memberAliInfo($app_auth_code, $state)
    {
        $isvconfig = new AlipayIsvConfigController();
        $config = $isvconfig->AlipayIsvConfig($state['config_id']);

        //1.初始化参数配置
        $aop = new AopClient();
        $aop->apiVersion = "2.0";
        $aop->appId = $config->app_id;
        $aop->rsaPrivateKey = $config->rsa_private_key;
        $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
        $aop->signType = "RSA2";//升级算法
        $aop->gatewayUrl = $config->alipay_gateway;
        $aop->format = "json";
        $aop->charset = "GBK";

        $obj = new AlipaySystemOauthTokenRequest();
        $obj->setApiVersion('2.0');
        $obj->setCode($app_auth_code);
        $obj->setGrantType("authorization_code");

        try {
            $data = $aop->execute($obj);
            $re = $data->alipay_system_oauth_token_response;

            return [
                'status' => 1,
                'data' => [
                    'open_id' => $re->user_id
                ]
            ];
        } catch (\Exception $e) {
            return [
                'status' => 2,
                'message' => '<h1>配置出错检查一下支付宝应用配置<h1>' . $e->getMessage() . $e->getFile() . $e->getLine()
            ];
        }
    }


}
